import re
from rest_framework.viewsets import ViewSet, GenericViewSet
from rest_framework.mixins import CreateModelMixin
from rest_framework.decorators import action
from django.conf import settings
from django.core.cache import cache
from . import serializer
from luffy_api.utils.response import APIResponse
from . import models
from luffy_api.libs.tx_sms.send import get_code, send_message
from .throttlings import SMSThrottling


class LoginView(ViewSet):
    # 登录接口
    @action(methods=('post',), detail=False)
    def login(self, request, *args, **kwargs):
        ser = serializer.UserModelSerializer(data=request.data)
        if ser.is_valid():
            token = ser.context['token']
            username = ser.context['user'].username
            return APIResponse(token=token, username=username)
        else:
            return APIResponse(code=0, msg=ser.errors)

    # 短信验证码登录
    @action(methods=('post',), detail=False)
    def code_login(self, request, *args, **kwargs):
        ser = serializer.CodeUserSerializer(data=request.data)
        if ser.is_valid():
            token = ser.context['token']
            username = ser.context['user'].username
            return APIResponse(token=token, username=username)
        else:
            return APIResponse(code=0, msg=ser.errors)

    # 校验手机号是否存在接口
    @action(methods=('get',), detail=False)
    def check_telephone(self, request, *args, **kwargs):
        telephone = request.query_params.get('telephone')
        if not re.match('^1[3-9][0-9]{9}$', telephone):
            return APIResponse(code=0, msg='手机号不合法')
        try:
            models.User.objects.get(telephone=telephone)
            return APIResponse()
        except:
            return APIResponse(code=0, msg='该手机号不存在')


# 短信验证码发送接口
class SendSmsView(ViewSet):
    throttle_classes = [SMSThrottling]

    @action(methods=('get',), detail=False)
    def send(self, request, *args, **kwargs):
        telephone = request.query_params.get('telephone')
        if not re.match('^1[3-9][0-9]{9}', telephone):
            return APIResponse(code=0, msg='手机号不合法')
        code = get_code()
        cache.set(settings.PHONE_CACHE_KEY % telephone, code, 180)
        result = send_message(telephone, code)
        if result:
            return APIResponse(msg='短信验证码发送成功')
        else:
            return APIResponse(code=0, msg='短信验证码发送失败')


class RegisterView(GenericViewSet, CreateModelMixin):
    queryset = models.User.objects.all()
    serializer_class = serializer.UserRegisterSerializer

    def create(self, request, *args, **kwargs):
        response = super().create(request, *args, **kwargs)
        username = response.data.get('username')
        return APIResponse(msg='注册成功', username=username)
